# 按下btn让led变亮直到最亮, 抬起保持亮度, 再按下变暗直到不亮
# channel = GP.wait_for_edge(pin_btn,GP.BOTH,timeout=500) 只对edge有反应,返回引脚的编号
# pin 11:G17 button
# pin 12:G18 red led
# pin 13:G27 green led
import RPi.GPIO as GP
import time

pin_green = 13
pin_btn = 11
pin_red = 12

def start():
    GP.setmode(GP.BOARD)
    GP.setwarnings(False)
    GP.setup(pin_btn, GP.IN,pull_up_down=GP.PUD_UP)
    GP.setup(pin_red, GP.OUT)


def turnon(x=-1):
    GP.output(pin_red,1)
    # print('on')
    
def turnoff(x=-1):
    GP.output(pin_red,0)
    # print('off')

def loop():
    red_p = GP.PWM(pin_red,200)
    red_p.start(0)
    lighten = 0
    turn_light = True
    while True:
        # timetout:探测频率毫秒
        # channel = GP.wait_for_edge(pin_btn,GP.BOTH,timeout=500)
        channel = GP.wait_for_edge(pin_btn,GP.RISING,timeout=500) # 抬起 
        # channel = GP.wait_for_edge(pin_btn,GP.FALLING,timeout=500) # 按下
        # print(channel)
        if channel: # 按下状态
            turn_light = not turn_light
        if turn_light and lighten <100:
            lighten+=5
        elif not turn_light and lighten>0:
            lighten-=5
        red_p.ChangeDutyCycle(lighten)
            # turnon()
        # else:
            # turnoff()
        print(lighten)
        # print(turn_light)


def close():
    GP.output(pin_red,0)
    GP.cleanup()


if __name__ == '__main__':
    start()
    try:
        loop()
    except Exception as e:
        print(e)
        close()

